<?php

namespace App\Http\Controllers\User;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Components\SmsComponent;
use App\Http\Components\RongCloudComponent;
use App\Http\Components\UserComponent;
use App\Http\Components\MessageComponent;
use DB;
use App\Models\UserModel;
use App\Models\UserAccountModel;
use App\Models\UserSettingModel;
use App\Models\UserProfileModel;
use App\Models\DataConfigModel;
use App\Models\AccountRecordModel;
use App\library\UtilFunction;

/**
 * 用户注册接口
 */
class RegisterController extends UserController{

    public function __construct(){
        parent::__construct();        
    }

    /*版本控制，对应app版本跳转对应接口*/
    public function version_invoke($function,Request $request){
        $appversion = $request->input('appversion');
        $apptype = $request->input('apptype');
        if ($appversion && $apptype) {
            try{

                return call_user_func_array(array($this,$function), array($request));
            }catch(\Exception $e){
                return $this->json('0','系统错误'.$e->getMessage());
            }
        }else{
            return $this->json('102','该app版本下无此接口，请更新app');
        }
    }

    /**
     *步骤1
     */
    public function step1(Request $request){

        $customAttr = [
            'username' => '手机号',
            'check_code' => '验证码',
        ];
        /*暂时不做校验*/
        $this->validate($request, [
            'username' => 'required|numeric',
            'check_code' => 'required',
        ],[ ], $customAttr);

        // 用户名
        $phone = $request->input('username');
        // 验证码
        $check_code = $request->input('check_code');
        $invite_code = $request->input('invite_code');  //邀请码
        //设备来源
        $apptype = $request->input('apptype');
        if(!in_array($apptype,array('ios','android','h5'))){
            return $this->json('0','设备来源输入有误!');
        }


        //判断验证码是否正确
        if($check_code != '1111'){
            $sms = new SmsComponent();
            $sms_status = $sms->verify_check_code($phone,$check_code,'register');
        }else{
            $sms_status = true;
        }

        //获取邀请码用户
        $master_id = 0;
        if(!empty($invite_code)){
            $master = UserProfileModel::select(['user_id'])->where("invite_code",$invite_code)->first();
            if($master){
                $master = $master->toArray();
                $master_id = $master['user_id'];
            }else{
                return $this->json('0','邀请码输入有误!');
            }
        }


        if ($sms_status) {

            //判断手机号是否注册
            $user = UserModel::where('phone',$phone)->first();
            if($user && $user['status'] == 1){  //已经注册
                return $this->json('0','该手机号已经注册!');
            }elseif($user){
                $app_login_time = date("Y-m-d H:i:s");
                $user->app_login_time = $app_login_time;
                $user->app_type = $apptype;

                $user->saveOrFail();
                $user_token = UserComponent::get_token($phone,$app_login_time,$apptype);
                $data = array(
                    "user_id"=>$user["user_id"],
                    "phone"=>$phone,
                    'user_token'=>$user_token,
                );
                return $this->json('1','验证成功!',$data);
            }else{
                $userModel = new UserModel();
                $app_login_time = date("Y-m-d H:i:s");
                $userModel->app_login_time = $app_login_time;
                $userModel->phone = $phone;
                $userModel->app_type = $apptype;
                if($userModel->saveOrFail()){
                    $user_id = $userModel->user_id;
                    //默认开启提醒开关
                    if ($userAccount = UserAccountModel::whereUserId($user_id)) {
                        $userAccount = new UserAccountModel();
                        $userAccount->user_id = $user_id;
                        $userAccount->saveOrFail();
                    }
                    //默认开启提醒开关
                    if ($userSetting = userSettingModel::whereUserId($user_id)) {
                        $userSetting = new userSettingModel();
                        $userSetting->user_id = $user_id;
                        $userSetting->saveOrFail();
                    }


                    //默认开启提醒开关
                    if ($userProfile = userProfileModel::whereUserId($user_id)) {
                        $userProfile = new userProfileModel();
                        $userProfile->user_id = $user_id;
                        $userProfile->phone = $phone;
                        $userProfile->invite_code = rand(1000000,9999999);
                        $userProfile->aotu_id = rand(1000000000,9999999999);
                        $userProfile->master_id = $master_id;
                        if(!empty($master_id) && isset($master)){
                            $master_id2 = $master["master_id"];
                            $userProfile->master_id2 = $master_id2;
                            if(!empty($master_id2)){
                                $master2 = UserProfileModel::where("user_id",$master_id2)->first();
                                if($master2 && !empty($master2->master_id)){
                                    $userProfile->master_id3 = $master2->master_id;
                                }
                            }

                        }
                        $userProfile->saveOrFail();
                    }
                    $user_token = UserComponent::get_token($phone,$app_login_time,$apptype);
                    $data = array(
                        "user_id"=>$user_id,
                        "phone"=>$phone,
                        'user_token'=>$user_token,
                    );
                    return $this->json('1','验证成功',$data);
                }else{
                    return $this->json('0','注册失败');
                }
            }

        }else{
            return $this->json('0',$sms->error_msg);
        }
    }
    /**
     *步骤2
     * 人脸识别验证
     */
    public function step2(Request $request){
        $user = UserComponent::check_token($request);
        $user_id = $user['user_id'];
        $face_auth = $request->input('face_auth');  //1 人脸识别成功
        $user = UserProfileModel::where('user_id',$user_id)->first();
        if($user){
            $user->face_auth = $face_auth;
            $result = $user->saveOrFail();
            if($result){
                return $this->json('1','保存成功');
            }else{
                return $this->json('0','保存失败');
            }
        }else{
            return $this->json('0','用户数据获取失败');
        }
    }

    /**
     * 保存用户信息
     */
    public function step3(Request $request){
        $user = UserComponent::check_token($request);
        $user_id = $user['user_id'];
        $nick_name = $request->input('nick_name');  //昵称
        $gender = $request->input('gender');  //性别   1 男,2 女
        $birth =  $request->input('birth'); //出身年月

        if(empty($nick_name)){
            return $this->json('0','昵称不能为空');
        }
        if(empty($gender) || !in_array($gender,array(1,2))){
            return $this->json('0','性别输入有误!');
        }
        if(empty($birth)){
            return $this->json('0','出身年月输入有误');
        }
        $age = UtilFunction::date_age($birth);
        $userProfile = UserProfileModel::where('user_id',$user_id)->first();
        if($userProfile){
            if(empty($userProfile->avatar)){
                return $this->json('0','请先上传头像');
            }
            $avatar = UtilFunction::getUrlImg($userProfile->avatar);
            //注册融云
            if(empty($userProfile->message_token)){
                $message_token = RongCloudComponent::register($user_id,$nick_name,$avatar);
                $userProfile->message_token = $message_token;
            }else{
                RongCloudComponent::update($user_id,$nick_name,$avatar);
                $message_token = $userProfile->message_token;
            }
            $userProfile->nick_name = $nick_name;
            $userProfile->gender = $gender;
            $userProfile->birth = $birth;
            $userProfile->age = $age;
            $result = $userProfile->saveOrFail();
            if($result){
                UserProfileModel::where("user_id",$user_id)->increment("credit_num",40);
                return $this->json('1','保存成功',$message_token);
            }else{
                return $this->json('0','保存失败');
            }
        }else{
            return $this->json('0','用户信息获取失败');
        }
    }

}
